package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"good_srv/good"
	"good_srv/internal/svc"
	"good_srv/models"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *good.OrderAddRequest) (*good.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	goods := models.Good{
		Model: gorm.Model{
			ID: uint(in.GoodsId),
		},
	}
	if err = goods.Detail(); err != nil {
		logx.Error("商品信息获取失败")
		return nil, fmt.Errorf("商品信息获取失败")
	}
	//库存是否充足
	if in.Num > goods.Stock {
		logx.Error("库存不充足")
		return nil, fmt.Errorf("库存不充足")
	}
	db := models.DB
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err = tx.Error; err != nil {
		return nil, err
	}

	//生成订单
	orders := models.Order{
		UserId:  in.UserId,
		OrderSn: uuid.NewString(),
		Amount:  goods.Price * float64(goods.Stock),
	}
	if err = orders.Create(tx); err != nil {
		tx.Rollback()
		return nil, err
	}
	//生成订单商品
	orderGoods := models.OrderGoods{
		OrderId:    int(goods.ID),
		GoodsId:    int(in.GoodsId),
		GoodsTitle: goods.Title,
		GoodsNum:   int(in.Num),
		GoodsPrice: goods.Price,
	}
	if err = orderGoods.Create(tx); err != nil {
		tx.Rollback()
		return nil, err
	}

	return &good.OrderAddResponse{}, nil
}
